package bf.util;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

public class BF2Java {

	static int methodCount = 0;
	
	public static void main(String[] args) throws IOException {
		FileReader reader = new FileReader(args[0]);
		PrintWriter writer = new PrintWriter(new FileWriter(args[1]));
		genMethod(reader, writer);
		reader.close();
		writer.close();
	}

	private static void genMethod(FileReader reader, PrintWriter writer)
			throws IOException {
		StringWriter stringWriter = new StringWriter();
		PrintWriter contentWriter = new PrintWriter(stringWriter);
		contentWriter.println("public void " + getName() + "() {");
		int size = 0;
		int read;
		ParsePE:
		while((read = reader.read()) != -1) {
			char cmd = (char)read;
			switch(cmd) {
				case '>':
					contentWriter.println("PI();");
					break;
				case '<':
					contentWriter.println("PD();");
					break;
				case '+':
					contentWriter.println("CI();");
					break;
				case '-':
					contentWriter.println("CD();");
					break;
				case '.':
					contentWriter.println("OC();");
					break;
				case '[':
					methodCount++;
					contentWriter.println("while(cell[pointer] != 0) {");
					contentWriter.println(getName() + "();");
					contentWriter.println("}");
					genMethod(reader, writer);
					break;
				case ']':
//					contentWriter.println("}");
					break ParsePE;
//					break;
				default:
	//				throw new RuntimeException("Unknown command!");
					System.out.println("Ignore: " + cmd);
					break;
			}
			if(size++ > 1000) {
				methodCount++;
				contentWriter.println(getName() + "();");
				genMethod(reader, writer);
			}
		}
		contentWriter.println("}");
		writer.println(stringWriter.toString());
		
	}
	
	private static String getName() {
		String name = "run";
		if(methodCount != 0) {
			name = name.concat("" + methodCount);
		}
		return name;
	}
}
